﻿#include "questionfactory.h"
#include "question/question.h"
#include "question/singlechoicequestin.h"
#include "question/judgequestion.h"

QuestionFactory::QuestionFactory(QObject *parent)
    : QObject{parent}
{}


Question *QuestionFactory::createQuestion(const QJsonObject &json, QObject *parent)
{
    // 验证JSON对象是否包含必要字段
    if (!json.contains("id")) {
        qWarning() << u8"问题JSON缺少必填字段:id";
        return nullptr;
    }
    
    // 首先尝试使用questionTypeId字段（数字类型）
    if (json.contains("questionTypeId")) {
        int typeId = json.value("questionTypeId").toInt();
        qDebug() << "Creating question with typeId:" << typeId;
        
        if (typeId == Question::TYPE_SINGLE_CHOICE) {
            SingleChoiceQuestin *question = new SingleChoiceQuestin(parent);
            if (question->fromJson(json)) {
                return question;
            }
            delete question;
            return nullptr;
        }
        else if (typeId == Question::TYPE_JUDGE) {
            JudgeQuestion *question = new JudgeQuestion(parent);
            if (question->fromJson(json)) {
                return question;
            }
            delete question;
            return nullptr;
        }
        else {
            qWarning() << u8"未知题型:" << typeId;
        }
    }
    // 如果没有questionTypeId字段，回退到使用questionTypeCaption字段（字符串类型）以保持兼容性
    else if (json.contains("questionTypeCaption")) {
        QString typeCaption = json.value("questionTypeCaption").toString();
        qDebug() << u8"创建题型为:" << typeCaption << u8"";
        
        if (typeCaption == u8"单选题") {
            SingleChoiceQuestin *question = new SingleChoiceQuestin(parent);
            if (question->fromJson(json)) {
                return question;
            }
            delete question;
            return nullptr;
        }
        else if (typeCaption == u8"判断题") {
            JudgeQuestion *question = new JudgeQuestion(parent);
            if (question->fromJson(json)) {
                return question;
            }
            delete question;
            return nullptr;
        }
        else {
            qWarning() << u8"未知题型:" << typeCaption;
        }
    }
    else {
        qWarning() << u8"问题JSON缺少ID的questionTypeId和questionTypeCaption字段" << json.value("id").toInt();
    }
    return nullptr;
}

